/*
 * Created on 2005-3-1
 */
package com.hd123.rumba.runtime;

import java.io.Serializable;

import com.hd123.rumba.exception.StringTooLongException;
import com.hd123.rumba.util.StringUtil;

/**
 * @author caili
 */
public class Persistent implements Serializable, Comparable, IPersistent {
  protected String uuid;

  /** uuid长度。允许派生类改变uuid属性的长度。 */
  protected int lengthUuid = CPersistent.LENGTH_UUID;

  /** @deprecated */
  public static final int LENGTH_UUID = CPersistent.LENGTH_UUID;

  public String getUuid() {
    return uuid;
  }

  public void setUuid(String uuid) throws StringTooLongException {
    if (uuid != null)
      uuid = CPersistent.truncate(uuid, lengthUuid, "uuid", CPersistent.CAPTION_UUID);
    this.uuid = uuid;
  }

  public int hashCode() {
    int i = 0;
    if (getUuid() != null) {
      i = getUuid().hashCode();
    }
    return i;
  }

  public boolean equals(Object obj) {
    boolean b = super.equals(obj);
    if (obj != null) {
      if (obj instanceof Persistent) {
        Persistent p = (Persistent) obj;
        if (getUuid() != null && p.getUuid() != null) {
          b = getUuid().equals(((Persistent) obj).getUuid());
        }
      } else if (obj instanceof IPersistent) {
        try {
          IPersistent p = (IPersistent) obj;
          if (getUuid() != null && p.getUuid() != null) {
            b = getUuid().equals(p.getUuid());
          }
        } catch (Exception e) {
          b = false;
        }
      }
    }
    return b;
  }

  public int compareTo(Object obj) {
    if (obj == null)
      return 1;
    if (!(obj instanceof Persistent))
      return 1;
    if (((Persistent) obj).getUuid() == null) {
      if (getUuid() == null)
        return 0;
      else
        return 1;
    } else {
      if (getUuid() == null)
        return -1;
      else
        return getUuid().compareTo(((Persistent) obj).getUuid());
    }
  }

  /**
   * 使得s的字节数不超过length. s可包含汉字.
   * 
   * @param s
   * @param length
   * @return
   */
  public static String truncate(String s, int length, String tag, String name)
      throws StringTooLongException {
    return StringUtil.truncate(s, length, tag, name);
  }

  public static final String NOTEXIST = "不存在";

  public boolean isEmpty() {
    return NOTEXIST.equals(getUuid());
  }

}
